package com.sparrow.common.cron.domain;


import com.sparrow.common.util.TimeUtil;
import org.quartz.CronExpression;

import java.lang.reflect.Method;
import java.util.Date;

public class CronTask implements Runnable {

    private Object object;
    private Method method;
    private CronExpression cronExpression;

    private long nextTime;

    public CronTask(Object object, Method method) {
        this.object = object;
        this.method = method;
    }

    public void setCronExpression(org.quartz.CronExpression cronExpression) {
        this.cronExpression = cronExpression;
    }

    public CronExpression getCronExpression() {
        return cronExpression;
    }

    public void invoke() {
        try {
            method.invoke(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void setNextTime(long nextTime) {
        this.nextTime = nextTime;
    }

    public long getNextTime() {
        return nextTime;
    }

    @Override
    public void run() {
        invoke();
    }

    public long getDelay() {
        return nextTime - System.currentTimeMillis();
    }

    public void initTriggerTime() {
        Date date = getCronExpression().getNextValidTimeAfter(new Date(System.currentTimeMillis()));
        setNextTime(date.getTime());
    }
}
